package com.module.compose.base.net

import androidx.lifecycle.ViewModel
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory


object Http {
    /**
     * 日志打印拦截器
     */
    private val logger = HttpLoggingInterceptor()

    /**
     * okhttp客户端
     */
    private val client: OkHttpClient

    /**
     * Retrofit实例
     */
    private val retrofit: Retrofit

    /**
     * API缓存，缓存已创建过的api对象，拿空间换时间的一种做法
     */
    private val apiCache = mutableMapOf<String, Any>()

    /**
     * 初始化
     */
    init {
        logger.level = HttpLoggingInterceptor.Level.BODY

        client = OkHttpClient
            .Builder()
            .addInterceptor(logger)
            .build()

        retrofit = Retrofit
            .Builder()
            .baseUrl("https://www.wanandroid.com/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    /**
     * 注入viewModel
     */
    fun inject(viewModel: ViewModel) {
        /**
         * 获取需要注入对象的class对象
         */
        val clazz = viewModel::class.java

        /**
         * 获取类的成员变量，包括私有
         */
        val fields = clazz.declaredFields

        /**
         * 遍历成员变量，找到被@API注解的变量
         */
        fields.forEach {
            if (it.isAnnotationPresent(API::class.java)) {
                //开放访问权限
                it.isAccessible = true
                try {
                    //为被注解的成员变量赋值
                    it.set(viewModel, create(it.type))
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    /**
     * 获取实例
     * @param clazz api的class对象
     */
    private fun <T> create(clazz: Class<T>): T {

        if (apiCache[clazz.name] == null) {
            apiCache[clazz.name] = retrofit.create(clazz)!!
        }
        return apiCache[clazz.name] as T
    }
}